﻿using System;
using System.Collections.Generic;
using System.Windows;
using Baosight.Platform.Core;
using Baosight.Platform.Core.ServiceModel;
using Baosight.Platform.Core.UI.Controls;
using Baosight.ZNH.ZMCommon;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Baosight.ZNH.ZMCP.UI.Blocks;
using Baosight.ZNH.ZMCP.UI.PopWindows;
using Telerik.Windows.Controls;
using System.Windows.Controls;
using System.Windows.Browser;

namespace Baosight.ZNH.ZMCP.UI
{
    /// <summary>
    /// 采煤专业计划主表
    /// </summary>
    /// Title:ZMCP01
    /// Copyright:Baosight Software LTD.co Copyright (c) 2011
    /// Company:上海宝信软件股份有限公司
    /// Author: 张小飞
    /// Version: 1.0
    /// History:
    ///       2011-10-19  张小飞   [创建]
    ///  
    public partial class ZMCP01 : EFViewCmes
    {

        ProfessionalPlanBlock block = new ProfessionalPlanBlock();
        private string actionType;

        public ZMCP01()
        {
            InitializeComponent();
            base.BeforeAction += OnBeforeAction;
        }

        /// <summary>
        /// 新增/修改前设置属性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnBeforeAction(object sender, EventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.EFGridCheckedRows = this.grid.GetCheckedEIRows();
            base.ViewProperty = _view;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="initData"></param>
        public override void Initialize(Platform.Core.EIInfo initData)
        {
            initData.AddBlock(block.getPlanStatus("cmes.cp.planStatus", true));
            initData.AddBlock(block.getPlanMonth("cmes.cp.planMonth", true));
            base.Initialize(initData);
        }

        /// <summary>
        /// 点击新增按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnInsertButtonClick(object sender, RoutedEventArgs e)
        {
            EIInfo eiInfo = new EIInfo();
            base.OnInsertButtonClickPopup(eiInfo, "采煤专业计划-新增", "insert", null, sender, e);
        }

        /// <summary>
        /// 点击修改按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnUpdateButtonClick(object sender, RoutedEventArgs e)
        {
            IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();
            EIInfo eiInfo = new EIInfo();
            EIBlock eIBlock = new EIBlock("result");

            EIRow row = new EIRow();
            if (_list.Count > 0)
            {
                row = BaseTools.GetEIRowByOldEIRow(this.EIDataContext.GetBlock("result").GetColumns(), _list[0]);
            }

            eIBlock.SetRow(0, row);
            eiInfo.AddBlock(eIBlock);

            this.actionType = "update";
            base.OnUpdateButtonClickPopup(eiInfo, "采煤专业计划-修改", "update", null, sender, e);
        }

        /// <summary>
        /// 删除按钮执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnDeleteButtonClick(object sender, RoutedEventArgs e)
        {
            this.actionType = "delete";
            base.OnDeleteButtonClick(sender, e);
        }

        /// <summary>
        /// 点击上报事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnReportButtonClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            if (BeforeAction != null)
            {
                BeforeAction.Invoke(null, null);
            }

            int count = this.ViewProperty.EFGridCheckedRows.Count;
            if (count <= 0)
            {
                this.OpenEFWindowAlert("请选择一条记录进行上报！", true);
                return;
            }
            else if (count > 1)
            {
                this.OpenEFWindowAlert("最多只能选择一条记录进行上报！", true);
                return;
            }
            else
            {
                if ("上报".Equals(this.ViewProperty.EFGridCheckedRows[0]["fdPlanStatus"].ToString()))
                {
                    base.OpenEFWindowAlert("已经上报的记录，不能再次上报！", true);
                    return;
                }
                else
                {
                    DialogParameters param = this.ModelDialogParameters("Confirm", "确定所选择上报的记录？");
                    param.Closed = ModifyConfirmClosed;
                    EFWindow.Confirm(param);
                }
            }

        }

        /// <summary>
        /// “改变状态”按钮的确认框，点击确认按钮执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ModifyConfirmClosed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == null || !e.DialogResult.Value)
            {
                this.TempButtonOpen(true);//取消后，“改变状态”按钮生效
                return;
            }
            if (e.DialogResult.Value)
            {
                base.Submit(OperationMode.Update, "ZMCP01", "report", DataRange.CheckedItems, DoModifyOperationCompleted);
            }
        }

        /// <summary>
        /// 执行修改“改变状态”后的回调方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private new void DoModifyOperationCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo inInfo = e.EIInfo;
            if (inInfo.Status == -1)
            {
                string _msg;
                if (inInfo.GetMsg() == null || inInfo.GetMsg() == "")
                {
                    _msg = "操作失败！";
                }
                else
                {
                    _msg = inInfo.GetMsg();
                }

                this.OpenEFWindowAlert(_msg, true);//修改状态按钮执行失败后，按钮生效
                return;
            }
            else
            {
                base.UpdateData(e.EIInfo);
                this.TempButtonOpen(true);//修改状态按钮执行成功后，按钮生效

                this.UpdateHomePageData(e.EIInfo);
                this.AfterMethod(e.EIInfo);
            }
        }

        /// <summary>
        /// 打印某个月的报表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnPrintButtonClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            if (BeforeAction != null)
            {
                BeforeAction.Invoke(null, null);
            }

            int count = this.ViewProperty.EFGridCheckedRows.Count;
            if (count <= 0)
            {
                this.OpenEFWindowAlert("请选择一条记录进行打印！", true);
                return;
            }
            else if (count > 1)
            {
                this.OpenEFWindowAlert("只能选择一条记录进行打印！", true);
                return;
            }
            else
            {
                string fdKeyId = this.grid.GetCheckedEIRows()[0]["fdKeyId"].ToString() ;
                string fdPlanYear = this.grid.GetCheckedEIRows()[0]["fdPlanYear"].ToString();
                string fdPlanMonth = this.grid.GetCheckedEIRows()[0]["fdPlanMonth"].ToString();
                Uri uri = Uploader.ConstructAbsoluteUri("../admin/RunmaxReport.jsp?projectName=ProfessionalPlan&reportName=professionalCMReport&fdKeyId=" + fdKeyId + "&year=" + fdPlanYear + "&month=" + fdPlanMonth);
                HtmlPage.Window.Navigate(uri, "_blank");
                base.TempButtonOpen(true);//按钮生效
            }
            
        }
        /// <summary>
        /// 删除,修改前的判断
        /// </summary>
        /// <param name="rowList"></param>
        /// <returns></returns>
        public override bool BeforeMethod(List<EIRow> _eIRows)
        {
            bool Flag = true;
            if ("update".Equals(this.actionType))
            {
                if (!"草拟".Equals(_eIRows[0]["fdPlanStatus"].ToString()))
                {
                    base.OpenEFWindowAlert("只能对草拟的记录进行修改！", true);
                    Flag = false;
                }
            }
            else if ("delete".Equals(this.actionType))
            {
                foreach (var row in _eIRows)
                {
                    if (!"草拟".Equals(row["fdPlanStatus"].ToString()))
                    {
                        base.OpenEFWindowAlert("只能对草拟的记录进行删除！", true);
                        Flag = false;
                        break;
                    }
                }
            }
            return Flag;
        }

        /// <summary>
        /// 新增或修改之前的数据传输
        /// 构造新增页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        public override void OpenPopup(EIInfo _eIInfo, string _title, string _dialogType, string _args)
        {
            ProfessionalPlanCM professionalPlan = new ProfessionalPlanCM(_dialogType);//构造一个新的修改页面
            professionalPlan.EIDataContext = new Platform.Core.UI.EIDataContext();

            _eIInfo.AddBlock(block.getPlanMonth("cmes.cp.planMonth", false));
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.cp.department"));

            professionalPlan.EIDataContext.Update(_eIInfo);

            if("insert".Equals(_dialogType))
            {
                professionalPlan.fdPlanYear.Value = DateTime.Now.Year.ToString();
                professionalPlan.fdPlanMonth.Value = DateTime.Now.Month.ToString();
                professionalPlan.fdEditDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
                professionalPlan.fdCreateDepartmentId.Value = this.EIDataContext.GetAttribute("fdCreateDepartmentId");
                professionalPlan.fdCreateDepartment.Value = this.EIDataContext.GetAttribute("fdCreateDepartment");
                professionalPlan.fdCreatorId.Value = this.EIDataContext.GetAttribute("fdCreatorId");
                professionalPlan.fdCreator.Value = this.EIDataContext.GetAttribute("fdCreator");
                //(professionalPlan.fdCreatorId.Content as CmesCustomView).Display = this.EIDataContext.GetAttribute("fdCreator");
            }

            CmesWindows _popup = new CmesWindows();//构造一个弹出页面
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = professionalPlan;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(CmesWindow_Closed);
            _popup.ShowDialog();//模态显示弹出窗口
           
        }

        /// <summary>
        /// 弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmesWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                //刷新Grid区域
                this.grid.Refresh();
            }

            //按钮生效
            base.TempButtonOpen(true);

            //超链接生效
            if (base.TempHyperlink != null)
            {
                base.TempHyperlink.IsEnabled = true;
                base.TempHyperlink = null;
            }
        }

        /// <summary>
        /// 选中主表一条记录，显示该条记录的从表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangeEventArgs e)
        {
            if (this.grid.SelectedItem != null)
            {
                var _id = this.grid.SelectedItem.GetType().GetProperty("fdKeyId").GetValue(this.grid.SelectedItem, null);
                var _planYear = this.grid.SelectedItem.GetType().GetProperty("fdPlanYear").GetValue(this.grid.SelectedItem, null);
                var _planMonth = this.grid.SelectedItem.GetType().GetProperty("fdPlanMonth").GetValue(this.grid.SelectedItem, null);
                var _planStatus = this.grid.SelectedItem.GetType().GetProperty("fdPlanStatus").GetValue(this.grid.SelectedItem, null);
               
                Dictionary<string, string> args = new Dictionary<string, string>();
                args.Add("fdProfessionalplanId", _id.ToString());
                args.Add("fdPlanYear", _planYear.ToString());
                args.Add("fdPlanMonth", _planMonth.ToString());
                args.Add("fdPlanStatus", _planStatus.ToString());
                this.container.LoadView<EFCustomViewContainerPanel>("ZMCP02", args);
            }
            else
            {
                this.container.ClearValue(EFCustomViewContainerPanel.ContentProperty);
            }
        }

        /// <summary>
        /// 重新基类的发布数据方法
        /// 刷新树节点
        /// </summary>
        /// <param name="data"></param>
        public override void OnEIDataPublished(EIInfo data)
        {
            if (null != this.grid.SelectedItem)
            {
                //刷新 “计划总量”
                EIInfo eiInfo = new EIInfo();
                eiInfo.Set("service", "ZMCP01");
                eiInfo.Set("method", "query");
                string fdKeyId = this.grid.SelectedItem.GetType().GetProperty("fdKeyId").GetValue(this.grid.SelectedItem, null) as string;
                EIBlock block = eiInfo.AddBlock(EIConstants.QueryStatusBlock);

                EIColumn column = new EIColumn();
                column.Name = "fdKeyId";
                block.AddColumn(column);

                EIRow row = new EIRow();
                row.Add("fdKeyId", fdKeyId);
                block.AddRow(row);

                HttpServiceAgent agent = new HttpServiceAgent();
                agent.CallService(eiInfo, CallServiceCompleted);
            }
        }

        /// <summary>
        /// 访问后台的回调
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CallServiceCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo == null || e.EIInfo.GetStatus() == -1)
            {
            }
            else
            {
                EIRow row = (this.grid.SelectedItem as UIBaseEntity).GetEIRow();
                row["fdPlanSum"] = e.EIInfo.GetBlock(EIConstants.ResultBlock).Get(0, "fdPlanSum");
            }
        }
    }
}
